import request from '../../utils/request'
Page({
  data: {
    phoneNumber: '',       // 手机号
    adminUserId: 0,        // 控制端用户ID
    userId: 0,             // 商城端用户ID
    adminUserName: '',     // 控制端用户名
    userName: '',          // 商城端用户名
    hasControlPermission: false,  // 是否有控制端权限
    hasMallPermission: false,     // 是否有商城端权限
    allCtrlPerms: [],      // 控制端权限列表
    allMallPerms: [],       // 商城端权限列表
    isControlAdmin: false
  },

  onLoad(options) {
    // 从跳转页面获取手机号参数
    const phoneNumber = options.phoneNumber;
    if (!phoneNumber) {
      wx.showToast({
        title: '缺少手机号参数',
        icon: 'none'
      });
      wx.navigateBack();
      return;
    }
    
    // 调用接口获取权限数据
    this.fetchPermissionData(phoneNumber);
  },

  // 获取权限数据
  fetchPermissionData(phoneNumber) {
    wx.showLoading({
      title: '加载中...'
    });
    
    request({
      url: 'perms?phoneNumber=' + phoneNumber,
      method: 'GET'
    })
    .then(res => {
      wx.hideLoading();
      
      if (res.code === 0 && res.data) {
        const data = res.data;
        this.setData({
          phoneNumber: data.cellphone,
          adminUserId: data.adminUserId,
          userId: data.userId,
          adminUserName: data.adminUserName || '',
          userName: data.userName || '',
          hasControlPermission: data.adminUserId !== 0 && data.enable,
          isControlAdmin: data.enable,
          hasMallPermission: data.userId !== 0,
          allCtrlPerms: data.allCtrlPerms || [],
          allMallPerms: data.allMallPerms || []
        });
      } else {
        wx.showToast({
          title: res.data.message || '获取权限数据失败',
          icon: 'none'
        });
      }
    })
    .catch(err => {
      wx.hideLoading();
      wx.showToast({
        title: err.message || '请求失败',
        icon: 'none'
      });
    });


  },

  // 控制端权限开关变化
  onControlPermissionChange(e) {
    const checked = e.detail.value;
    this.setData({
      hasControlPermission: checked,
      adminUserId: checked ? 1 : 0
    });
  },


    
  // 控制端管理人员勾选变化
  onControlAdminChange(e) {
    // console.log(e);
    const isChecked = !this.data.isControlAdmin; // 手动切换状态
    // this.setData({ isControlAdmin: isChecked });
    // console.log('当前状态:', isChecked);
    // 判断是否选中
    // const checked = e.detail.value;
    // console.log(checked);
    this.setData({
      isControlAdmin: isChecked
      // hasControlPermission: isChecked // 直接跟着同步
    });
  },

  // 控制端用户名输入
  onAdminNameInput(e) {
    this.setData({
      adminUserName: e.detail.value
    });
  },

  // 控制端权限项变化
  onCtrlPermChange(e) {
    const index = e.currentTarget.dataset.index;
    const allCtrlPerms = this.data.allCtrlPerms.slice(); // 拷贝数组，避免直接修改引用
  
    // 手动取反 selected 状态
    allCtrlPerms[index].selected = !allCtrlPerms[index].selected;
  
    this.setData({ allCtrlPerms });
  
    console.log('点击选中', allCtrlPerms[index]);
  },

  // 商城端权限项变化
  onMallPermChange(e) {
    const index = e.currentTarget.dataset.index;
    const allMallPerms = this.data.allMallPerms.slice();
    allMallPerms[index].selected = !allMallPerms[index].selected;
    this.setData({ allMallPerms });
    console.log('点击选中', allMallPerms[index]);
  },

  // 保存权限设置
  onSave() {
    const {
      phoneNumber,
      adminUserId,
      userId,
      adminUserName,
      allCtrlPerms,
      allMallPerms,
      isControlAdmin
    } = this.data;
    
    // 筛选选中的控制端权限ID
    const selectedCtrlPerms = allCtrlPerms
      .filter(item => item.selected)
      .map(item => item.id);
    
    // 筛选选中的商城端权限ID
    const selectedMallPerms = allMallPerms
      .filter(item => item.selected)
      .map(item => item.id);

      console.log('allCtrlPerms:', allCtrlPerms);
      console.log('allMallPerms:', allMallPerms);

      const selectedPerms = [
        ...selectedCtrlPerms,
        ...selectedMallPerms
      ];
    console.log("选中权限" + selectedPerms)

    wx.showLoading({
      title: '保存中...'
    });
    
    // 调用保存接口
    request({
      url: 'perms',
      method: 'PUT',
      data: {
        cellphone: phoneNumber,
        adminUserId,
        userId,
        adminUserName,
        enableControlAdmin: isControlAdmin,
        permIds: selectedPerms,
      }
    }).then((res) => {
      wx.hideLoading();
      
      wx.showToast({
        title: '保存成功',
        icon: 'success'
      });
      // 1.5秒后刷新上一页数据，但不跳转
      setTimeout(() => {
        const pages = getCurrentPages();
        if (pages.length > 1) {
          const prevPage = pages[pages.length - 2];
          prevPage.onLoad && prevPage.onLoad();
        }
      }, 300);
    }).catch((err) => {
      wx.hideLoading();
      wx.showToast({
        title: '保存失败',
        icon: 'none'
      });
    });
  },



  

  // 取消
  onCancel() {
    wx.navigateBack();
  }
});